/*
 * ============================================================================
 *
 *       Filename:  main.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2018年04月08日 14时38分25秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  jianxi sun (jianxi), ycsunjane@gmail.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

int main(int argc, char *argv[])
{
	if(argc < 4) {
		fprintf(stderr, "Usage: %s xor src dst(- stdout)\n", argv[0]);
		return -1;
	}

	long int xor;
	xor = strtol(argv[1], NULL, 0);

	FILE *in, *out;
	in = fopen(argv[2], "r");
	if(!in) {
		fprintf(stderr, "Fopen %s failed: %s(%d)\n",
			argv[2], strerror(errno), errno);
		return -1;
	}

	if(strcmp(argv[3], "-") == 0) {
		out = stdout;
	} else {
		out = fopen(argv[3], "w+");
		if(!out) {
			fprintf(stderr, "Fopen %s failed: %s(%d)\n",
				argv[3], strerror(errno), errno);
			return -1;
		}
	}

	uint8_t buf[1024];
	int i;
	size_t rsize;
	do {
		rsize = fread(buf, 1, 1023, in);
		if(rsize == 0)
			break;
		buf[rsize] = 0;
		for(i = 0; i < rsize; i++)
			buf[i] ^= xor;

		fwrite(buf, 1, rsize, out);
	}while(rsize);
	return 0;
}
